import router from './router'
import { useLoginUserState } from '@/stores/useLoginUserState.ts'
import { message } from 'ant-design-vue'

let firstGetLoginUser = true
router.beforeEach(async (to, from, next) => {
  const toUrl = to.fullPath
  if (toUrl === '/user/login' || toUrl === '/uer/regist' || toUrl === '/') {
    next()
    return
  }
  const loginUserStore = useLoginUserState()
  let loginUser = loginUserStore.loginUser
  if (firstGetLoginUser) {
    await loginUserStore.getLoginUser()
    loginUser = loginUserStore.loginUser
    firstGetLoginUser = false
  }
  if (toUrl.startsWith('/admin')) {
    if (!loginUser || loginUser.userRole !== 'admin') {
      message.error('没有权限访问')
      next('/')
    }
  }
  next()
})
